<?php

namespace app\api\controller;

use app\common\controller\Api;

use think\Db;
use app\admin\model\Course;
use app\admin\model\User;
use app\admin\model\UserCourse;
use app\common\model\WxPay;



class Order extends Api
{
    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';

    /**
     * 创建订单
     */
    public function createOrder()
    {
        $uid = $this->auth->id;
        $this->checkParam(['course_id','pay_type']);
        $user  = User::where('id',$uid)->find()->toArray();
        $course_id = $this->request->post('course_id');
        $pay_type = $this->request->post('pay_type');
        $courseInfo = Course::where('id', $course_id)->where('deletetime',null)->where('status',0)->find()->toArray();
        if (!$courseInfo) {
            $this->error(__('暂无课程无法生成订单'));
        }

        do{
            $order_no = create_order_code();
            $orderInfo = DB::name('order')->where('order_no','=',$order_no)->find();
        }while(!empty($orderInfo));
        $data = [
            'order_no' => $order_no,
            'venue_id' => $courseInfo['venue_id'],
            'user_id' => $uid,
            'course_id' => $course_id,
            'snapshot' => $courseInfo['name'].'-'.$courseInfo['day'].'天-价格'.$courseInfo['price'],
            'ctime' => time(),
            'price' => $courseInfo['price'],
            'pay_type' => $pay_type
        ];

        DB::name('order')->insert($data);
       // User::where('id',$uid)->update(['venue_id' => $courseInfo['venue_id']]);

        if ($pay_type == 0) {
            //储值金支付

            if ($user['money'] < $courseInfo['price']) {
                $this->error(__('储值金额不够，请先充值或者选择其他支付方式'));
            }
            Db::startTrans();
            $money = bcsub($user['money'], $courseInfo['price'], 2);

            $param = [
                'user_id' => $uid,
                'money' => $orderInfo['price'],
                'before' => $user['money'],
                'after' => $money,
                'memo' => '课程购买',
                'order_no' => $order_no,
                'createtime' => time()
            ];
            DB::name('user_money_log')->insert($param);
            User::where('id',$uid)->update(['money' => $money]);
            DB::name('order')->where('order_no',$order_no)->update(['status' => 1, 'ptime' => time()]);
            UserCourse::insert([
                'order_no' => $order_no,
                'venue_id' => $courseInfo['venue_id'],
                'user_id' => $uid,
                'course_id' => $course_id,
                'ctime' => time()
            ]);
            Db::commit();
            $this->success(__('支付成功'),['feefree'=>true]);
        } else {
            //免费课程插入新课

            if ($courseInfo['type'] == 2 || $courseInfo['price'] == 0) {
                $orderInfo = DB::name('order')->where('order_no','=',$order_no)->find();
                Db::startTrans();
                UserCourse::insert([
                    'order_no' => $orderInfo['order_no'],
                    'venue_id' => $orderInfo['venue_id'],
                    'user_id' => $orderInfo['user_id'],
                    'course_id' => $orderInfo['course_id'],
                    'ctime' => time()
                ]);
                DB::name('order')->where('order_no',$orderInfo['order_no'])->update(['status' => 1, 'pay_type' => 4, 'ptime' => time()]);
                Db::commit();
                $this->success(__('支付成功'),['feefree'=>true]);
            } else {
                $this->wxPay($order_no);
            }

        }
    }

    /*
     * 充值订单
     * */
    public function rechargeOrder()
    {
        $uid = $this->auth->id;
        $this->checkParam(['price']);
        $user  = User::where('id',$uid)->find()->toArray();
        $price = $this->request->post('price');

        do{
            $order_no = create_order_code();
            $orderInfo = DB::name('order')->where('order_no','=',$order_no)->find();
        }while(!empty($orderInfo));
        $data = [
            'order_no' => $order_no,
            'venue_id' => $user['venue_id'],
            'user_id' => $uid,
            'snapshot' => "充值金额-".$price."元",
            'ctime' => time(),
            'price' => $price,
            'pay_type' => 1,
            'type' => 1
        ];

        DB::name('order')->insert($data);

        /*假的充值*/
       /* $orderInfo = DB::name('order')->where('order_no','=',$order_no)->find();
        $userInfo = DB::name('user')->where('id', '=', $orderInfo['user_id'])->find();
        $newMoney = bcadd($userInfo['money'], $orderInfo['price'], 2);
        $data = [
            'user_id' => $userInfo['id'],
            'money' => $orderInfo['price'],
            'before' => $userInfo['money'],
            'after' => $newMoney,
            'memo' => '金额储值',
            'createtime' => time()
        ];
        DB::name('user_money_log')->insert($data);
        DB::name('user')->where('id',$userInfo['id'])->update(['money' => $newMoney]);
        $this->success(__('充值成功'));*/





        //微信支付
        $this->wxPay($order_no);

       // $this->success(__('订单创建成功'));
    }

    public function wxPay($oid){
        $uid = $this->auth->id;


        $orderInfo = Db::name('order')->where('order_no', $oid)->find();
        if ($orderInfo['user_id'] !=  $uid) {
            $this->error(__('订单不合法'));
        }
        if ($orderInfo['user_id'] == 1) {
            $this->error(__('订单已支付'));
        }

        if ($orderInfo['user_id'] == 2) {
            $this->error(__('订单已失效'));
        }
        $openid = Db::name('user')->where('id', $uid)->value('openid');
       // $openid = 'oM_JR5GAmik141tnMhLeWlUv2sgY';

        $pey_price = $orderInfo['price'] * 100;
        $wxPay = new WxPay();
        $wxPay->setBody($orderInfo['snapshot']);
        $wxPay->setOutTradeNo($orderInfo['order_no']);
        $wxPay->setAttach(json_encode(array('uid' => $orderInfo['user_id'], 'course_id' => $orderInfo['course_id'])));
        $wxPay->setTotalFee($pey_price);
        $wxPay->setProductId($orderInfo['course_id']);
        //$wxPay->setNotifyUrl(Config('wx.notify_url'));
        $wxPay->setTradeType("JSAPI");
        $wxPay->setOpenid($openid);

        $result = $wxPay->ready();
      //  dump($result);die;
        if ($result['return_code'] == 'FAIL') {
            $this->error(__($result["return_msg"]));
        }

        $result = $wxPay->getPaySign($result["prepay_id"]);
        $this->success(__('下单成功'), $result);
    }



    /*
     * 支付回调
     * */
    public function wxNotify(){
        $xml = file_get_contents("php://input");
        DB::name('pay_log')->insert(['log' => $xml, 'time' => date('Y-m-d H:i:s',time())]);
        $data = xmlToArray($xml);
        if ($data['return_code'] != "SUCCESS") return;

        $wxPay = new WxPay();
        if (!$wxPay->checkSign($data)) {
            echo "fail";
            return;
        }

        $orderInfo = DB::name('order')->where('order_no', '=', $data['out_trade_no'])->find();
        if (empty($orderInfo) || $orderInfo['status'] != 0) {
            echo "fail";
            exit();
        }

        Db::startTrans();
        //修改订单支付状态、支付方式与时间
        if ($orderInfo['type'] == 1) {
            $userInfo = DB::name('user')->where('id', '=', $orderInfo['user_id'])->find();
            $newMoney = bcadd($userInfo['money'], $orderInfo['price'], 2);
            $data = [
                'user_id' => $userInfo['id'],
                'money' => $orderInfo['price'],
                'before' => $userInfo['money'],
                'after' => $newMoney,
                'memo' => '金额储值',
                'order_no' => $orderInfo['order_no'],
                'createtime' => time()
            ];
            DB::name('user_money_log')->insert($data);
            DB::name('user')->where('id',$userInfo['id'])->update(['money' => $newMoney]);
        } else {
            //给用户插入课程
             UserCourse::insert([
                'order_no' => $orderInfo['order_no'],
                'venue_id' => $orderInfo['venue_id'],
                'user_id' => $orderInfo['user_id'],
                'course_id' => $orderInfo['course_id'],
                'ctime' => time()
            ]);
        }
        DB::name('order')->where('order_no',$orderInfo['order_no'])->update(['status' => 1, 'pay_type' => 1, 'ptime' => time()]);
        Db::commit();
        echo "success";


    }


}
